package com.by.yz.fragment;

import com.android.volley.toolbox.NetworkImageView;
import com.by.yz.App;
import com.by.yz.Register.DoctorREST;
import com.by.yz.activity.FamousDoctor;
import com.by.yz.activity.ManagerPatients;
import com.by.yz.activity.QuickAnswerActivity;
import com.by.yz.activity.diagnosis_bingming;
import com.by.yz.custom.CircleNetworkImageView;
import com.by.yz.entity.Account;
import com.by.yz.entity.Doctorbean;
import com.by.yz.entity.UserTest;
import com.by.yz.loginUtil.AccountRESTFul;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;



import com.bumptech.glide.Glide;
import com.by.yz.R;
import com.by.yz.activity.Famous_doctor_detail;
import com.by.yz.activity.FindDoctorActivity;
import com.by.yz.activity.HealthTopicActivity;
import com.by.yz.activity.QuickAskActivity;
import com.by.yz.common.MFGT;
import com.by.yz.custom.TechnologyTeamDividerItemDecoration;
import com.by.yz.loginUtil.UserRESTFul;
import com.by.yz.util.IsNetWork;
import com.by.yz.util.ToJSonObject;
import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;
import com.panxw.android.imageindicator.AutoPlayManager;
import com.panxw.android.imageindicator.ImageIndicatorView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;

import org.json.JSONArray;
import org.json.JSONException;


/**
 * 知道碎片界面
 *
 * @author wwj_748
 */
public class vehicleDiagnosisFragment extends Fragment implements View.OnClickListener {
    private MaterialRefreshLayout materialRefreshLayout;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    AutoPlayManager autoBrocastManager;

    View view;
    //顶部listview

    //底部listview
    LinearLayout doctor_museum;
    LinearLayout intelligent_diagnosis;
    LinearLayout disease_dictionary;
    RecyclerView recyclerView;
    SimpleStringRecyclerViewAdapter simpleStringRecyclerViewAdapter;
    List<Doctorbean> datas=new ArrayList<Doctorbean>();

//    List<TechnologyTeam> datas_top=new ArrayList<TechnologyTeam>();
    ImageIndicatorView imageIndicatorView;

    RelativeLayout health_topic_list;
    RelativeLayout quickanswer;
    RelativeLayout managerpatients;
    RelativeLayout quickack;
    RelativeLayout seekdoctor;
    UserTest userTest;
    Account account;
    int page;
    int doctorN = 0;
    IsNetWork isNetWork;


//                            _ooOoo_
//                           o8888888o
//                           88" . "88
//                           (| -_- |)
//                            O\ = /O
//                        ____/`---'\____
//                      .   ' \\| |// `.
//                       / \\||| : |||// \
//                     / _||||| -:- |||||- \
//                       | | \\\ - /// | |
//                     | \_| ''\---/'' | |
//                      \ .-\__ `-` ___/-. /
//                   ___`. .' /--.--\ `. . __
//                ."" '< `.___\_<|>_/___.' >'"".
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |
//                 \ \ `-. \_ __\ /__ _/ .-` / /
//         ======`-.____`-.___\_____/___.-`____.-'======
//                            `=---='
//
//         .............................................
//                  佛祖保佑             永无BUG
//          佛曰:
//                  写字楼里写字间，写字间里程序员；
//                  程序人员写程序，又拿程序换酒钱。
//                  酒醒只在网上坐，酒醉还来网下眠；
//                  酒醉酒醒日复日，网上网下年复年。
//                  但愿老死电脑间，不愿鞠躬老板前；
//                  奔驰宝马贵者趣，公交自行程序员。
//                  别人笑我忒疯癫，我笑自己命太贱；
//                  不见满街漂亮妹，哪个归得程序员？

    /**
     * Created by 吃饼干的国民党干部 on 2016/10/19.
     */

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
         view = inflater.inflate(R.layout.main_tab1_fragment, container, false);
        init();
        initDataTop();
        page=0;
        initData();
        initRefresh();
        return view;
    }
        private void initDataTop() {
            AccountRESTFul accountRESTFul=new AccountRESTFul();
            accountRESTFul.get(new AccountRESTFul.IhttpCb() {
                @Override
                public void ok(JSONObject response) {
                    JSONObject jsonObject=response;
                    account=ToJSonObject.jsonToBean(jsonObject.toString(),Account.class);
                    //login.setText(account.getLogin());

                    UserRESTFul userRESTFul=new UserRESTFul();
                    userRESTFul.getUser(account.getLogin(), new UserRESTFul.UserPOSTCallBack() {
                        @Override
                        public void ok(JSONObject response) throws JSONException {
                            Log.e("VDF-user",response.toString());
                            JSONObject jsonObject=response;
                            userTest=ToJSonObject.jsonToBean(jsonObject.toString(),UserTest.class);
                            if(userTest.getflag()){
                                quickack.setVisibility(View.GONE);
                                seekdoctor.setVisibility(View.GONE);
                                quickanswer.setVisibility(View.VISIBLE);
                                managerpatients.setVisibility(View.VISIBLE);
                            }
                        }
                        @Override
                        public void error(String response) {
                            Log.e("VDF-user-error","获取用户表失败"+response);
                        }
                    });
                }

                @Override
                public void error(String error) {
                    Log.e("PCF-account-error","授权失败"+error);
                }
            });

    }

    private void initData() {
                DoctorREST doctorREST=new DoctorREST();
                doctorREST.getDoctorRESTopage(page,new DoctorREST.MyGetCallBack() {
                    @Override
                    public void ok(JSONArray response) throws JSONException {
                        Doctorbean doctorbean;
                        doctorN = 0;
                        Log.e("response.length() = ",response.length()+"");
                        for(int i=0;i<response.length();i++){
                            JSONObject jsonObject= response.getJSONObject(i);
                            doctorbean= ToJSonObject.jsonToBean(jsonObject.toString(),Doctorbean.class);
                            if(doctorbean.getFlag()) {
                                doctorN++;
                                datas.add(doctorbean);
                            }
                        }
                        if(page != 0 && doctorN ==0){
                            Toast.makeText(getActivity(), "没有可以加载的了", Toast.LENGTH_SHORT).show();
                        }else if ( page !=0 && doctorN !=0){
                            Toast.makeText(getActivity(), "加载了"+doctorN+"条数据", Toast.LENGTH_SHORT).show();
                        }
                        page++;
                        simpleStringRecyclerViewAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void error(String error) {
                        Log.e("vdf-error","更新失败"+error);
                        Toast.makeText(getActivity(), "没有可以加载的了", Toast.LENGTH_SHORT).show();
                    }
                });

    }

    private void init() {
        //快速解答
        quickanswer=(RelativeLayout)view.findViewById(R.id.docmedicie_top_list_item);
        quickanswer.setOnClickListener(this);
        //管理我的患者
        managerpatients=(RelativeLayout)view.findViewById(R.id.docmedicie_top_list_item1);
        managerpatients.setOnClickListener(this);
        //在线咨询
        quickack=(RelativeLayout)view.findViewById(R.id.medicie_top_list_item);
        quickack.setOnClickListener(this);
        //找医生
        seekdoctor=(RelativeLayout)view.findViewById(R.id.medicie_top_list_item1);
        seekdoctor.setOnClickListener(this);
        //健康话题
        health_topic_list=(RelativeLayout)view.findViewById(R.id.medicie_top_list_item2);
        health_topic_list.setOnClickListener(this);
        //初始化只能诊断和名医馆ImageView
        doctor_museum=(LinearLayout) view.findViewById(R.id.doctor_museum) ;
        intelligent_diagnosis=(LinearLayout)view.findViewById(R.id.intelligent_diagnosis) ;
        doctor_museum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isNetWork.isNetworkAvailable(getActivity())) {
                    Context context = view.getContext();
                    Intent intent = new Intent(getActivity(), FamousDoctor.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("searchString", "");
                    intent.putExtras(bundle);
                    context.startActivity(intent);
                }else{
                    //无网络连接情况
                    new AlertDialog.Builder(getActivity())
                            .setTitle("提示!")
                            .setIcon(android.R.drawable.ic_dialog_info)
                            .setMessage("检测到您还没开启网络，请开启")
                            .setNegativeButton("取消", null)
                            .setPositiveButton("开启",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog,
                                                            int which) {
                                            startActivity(new Intent(
                                                    Settings.ACTION_WIRELESS_SETTINGS));// 进入无线网络配置界面
                                        }
                                    }).show();
                }
            }
        });
        intelligent_diagnosis.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isNetWork.isNetworkAvailable(getActivity())) {
                    Context context = view.getContext();
                    Intent intent = new Intent(getActivity(), diagnosis_bingming.class);
                    context.startActivity(intent);
                }else{
                    //无网络连接情况
                    new AlertDialog.Builder(getActivity())
                            .setTitle("提示!")
                            .setIcon(android.R.drawable.ic_dialog_info)
                            .setMessage("检测到您还没开启网络，请开启")
                            .setNegativeButton("取消", null)
                            .setPositiveButton("开启",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog,
                                                            int which) {
                                            startActivity(new Intent(
                                                    Settings.ACTION_WIRELESS_SETTINGS));// 进入无线网络配置界面
                                        }
                                    }).show();
                }
            }
        });

        //初始化底部Listview
        recyclerView=(RecyclerView) view.findViewById(R.id.recyclerview);
        recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext()));
        simpleStringRecyclerViewAdapter=new SimpleStringRecyclerViewAdapter(getActivity(),
                datas);
        recyclerView.setAdapter(simpleStringRecyclerViewAdapter);
        recyclerView.addItemDecoration(new TechnologyTeamDividerItemDecoration(this.getActivity(),TechnologyTeamDividerItemDecoration.VERTICAL_LIST));


        imageIndicatorView = (ImageIndicatorView)view.findViewById(R.id.indicate_view);
        final Integer[] resArray = new Integer[] { R.mipmap.health_topic,R.mipmap.health_topic,R.mipmap.health_topic, R.mipmap.health_topic };
        imageIndicatorView.setupLayoutByDrawable(resArray);
        imageIndicatorView.setIndicateStyle(ImageIndicatorView.INDICATE_USERGUIDE_STYLE);
        imageIndicatorView.show();

        materialRefreshLayout = (MaterialRefreshLayout) view.findViewById(R.id.MaterialRefreshLayout);
        materialRefreshLayout.setLoadMore(true);
        materialRefreshLayout.setWaveShow(false);
        materialRefreshLayout.setShowProgressBg(false);

        autoBrocastManager =  new AutoPlayManager(imageIndicatorView);
        autoBrocastManager.setBroadcastEnable(true);
        autoBrocastManager.setBroadCastTimes(50);//loop times
        autoBrocastManager.setBroadcastTimeIntevel(3 * 1000, 3 * 1000);//set first play time and interval
        autoBrocastManager.loop();
    }
    public void initRefresh(){

        materialRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {

            @Override
            public void onRefresh(final MaterialRefreshLayout materialRefreshLayout) {
                android.os.Handler handler=new android.os.Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        materialRefreshLayout.finishRefresh();
                    }
                },0);

            }
			@Override
			public void onRefreshLoadMore(final MaterialRefreshLayout materialRefreshLayout) {
				android.os.Handler handler=new android.os.Handler();
				handler.postDelayed(new Runnable() {
					@Override
					public void run() {
                        initData();
						/**
						 * 完成加载数据后，调用此方法，要不然刷新的效果不会消失
						 */
						materialRefreshLayout.finishRefreshLoadMore();
					}
				}, 3000);
			}
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.medicie_top_list_item:
                MFGT.startActivity(getActivity(),QuickAskActivity.class);
                break;
            case R.id.medicie_top_list_item1:
                MFGT.startActivity(getActivity(),FindDoctorActivity.class);
                break;
            case R.id.medicie_top_list_item2:
                Intent intent=new Intent(this.getActivity(),HealthTopicActivity.class);
                Bundle bundle=new Bundle();
                bundle.putSerializable("healthtopic",userTest);
                intent.putExtras(bundle);
                startActivity(intent);
//                MFGT.startActivity(getActivity(),HealthTopicActivity.class);
                break;
            case R.id.docmedicie_top_list_item:
                MFGT.startActivity(getActivity(),QuickAnswerActivity.class);
                break;
            case R.id.docmedicie_top_list_item1:
                MFGT.startActivity(getActivity(),ManagerPatients.class);
                break;
        }

    }

    public static class SimpleStringRecyclerViewAdapter
            extends RecyclerView.Adapter<SimpleStringRecyclerViewAdapter.ViewHolder> {

        private final TypedValue mTypedValue = new TypedValue();
        private int mBackground;
        private List<Doctorbean> mValues;



        public static class ViewHolder extends RecyclerView.ViewHolder {
            public Doctorbean tt;

            public final View mView;
            public final CircleNetworkImageView mImageView;
            public final TextView doctorName;
            public final TextView textHospital;
            public final TextView department;
            public final TextView instruc;
            public final TextView doctorPosition;


            public ViewHolder(View view) {
                super(view);
                mView = view;
                mImageView = (CircleNetworkImageView) view.findViewById(R.id.avatar);
                doctorName = (TextView) view.findViewById(R.id.doctorName);
                textHospital = (TextView) view.findViewById(R.id.textHospital);
                department = (TextView) view.findViewById(R.id.department);//隶属科室
                instruc =(TextView) view.findViewById(R.id.textSubDescripting);
                doctorPosition=(TextView)view.findViewById(R.id.doctorPosition);
            }
        }

        public Doctorbean getValueAt(int position) {
            return mValues.get(position);
        }

        public SimpleStringRecyclerViewAdapter(Context context, List<Doctorbean> items) {
            context.getTheme().resolveAttribute(R.attr.selectableItemBackground, mTypedValue, true);
            mBackground = mTypedValue.resourceId;
            mValues = items;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.home_page_list_item, parent, false);
           // view.setBackgroundResource(mBackground);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(final ViewHolder holder, int position) {

            holder.tt = mValues.get(position);
            holder.doctorName.setText(mValues.get(position).getDoctorname());
            holder.textHospital.setText(mValues.get(position).getTextHospital().getHospital());
            holder.department.setText(mValues.get(position).getDepartment().getDepartment());
            holder.instruc.setText(mValues.get(position).getResume());
            holder.doctorPosition.setText(mValues.get(position).getPosition());
            holder.mImageView.setDefaultImageResId(R.mipmap.login_logo1);
            holder.mImageView.setErrorImageResId(R.mipmap.login_error);
            holder.mImageView.setImageUrl(mValues.get(position).getmImageView(), App.imageLoader);
//            Glide.with(holder.mImageView.getContext())
//                    .load(mValues.get(position).getmImageView())
//                    .fitCenter()
//                    .into(holder.mImageView);
            holder.mView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Context context = v.getContext();
                    Intent intent = new Intent(context, Famous_doctor_detail.class);
//                    intent.putExtra(CheeseDetailActivity.EXTRA_NAME, holder.mBoundString);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("Doctor",holder.tt);
                    intent.putExtras(bundle);
                    context.startActivity(intent);
                }
            });

        }

        @Override
        public int getItemCount() {
            return mValues.size();
        }
    }

}
